﻿<!DOCTYPE html>
<html lang=en>
<head>
    <meta charset=utf-8>
    <meta http-equiv=X-UA-Compatible content="IE=edge">
    <meta name=viewport content="width=device-width,initial-scale=1">
    <title>SignalR</title>

    <script src="./js/signalr/dist/browser/signalr.js"></script>

</head>
<body>

    <label>用户：<input id="txtName" /></label>
    <button id="btnConnect">连接</button>
    <hr />
    <label>指定用户：<input id="txtDesc" /></label>
    <label>消息：<input id="txtMessage" /></label>
    <button id="btn">确定</button>
    <hr />
    <ul id="ulMsg">
    </ul>

    <script>
        var conn;
        document.getElementById("btnConnect").onclick = function () {
            var name = document.getElementById("txtName").value
            conn = new signalR.HubConnectionBuilder().withUrl(`/chathub?name=${name}`).build()
            conn.start()
            conn.on("ReceiveMessage", function (user, message) {
                var li = document.createElement("li")
                li.textContent = `${user}发来消息：${message}`
                document.getElementById("ulMsg").appendChild(li)
            })
        }
        document.getElementById("txtName").onkeypress = function (e) {
            if (e.keyCode !== 13) return
            document.getElementById("btnConnect").onclick()
        }




        function send() {
            var user = document.getElementById("txtDesc").value
            var msg = document.getElementById("txtMessage").value
            conn.invoke("SendMessage", user, msg).catch(err => console.error(err.toString()))
        }

        document.getElementById("btn").onclick = function (e) {
            send()
            e.preventDefault()
        }

        document.getElementById("txtDesc").onkeypress = function (e) {
            if (e.keyCode !== 13) return
            send()

        }
        document.getElementById("txtMessage").onkeypress = function (e) {
            if (e.keyCode !== 13) return
            send()
        }

    </script>
</body>
</html>